package com.haiyou.dc.thread.test1;

public class HappyCinema {

    public static void main(String[] args) {
        Cinema c = new Cinema(4, "开心电影院");
        new Thread(new Cunstomer(c, 2), "张三").start();
        new Thread(new Cunstomer(c, 3), "李四").start();
    }
}

/**
 * 顾客
 */
class Cunstomer implements Runnable {

    private Cinema cinema;
    private int seat;

    public Cunstomer(Cinema cinema, int seat) {
        this.cinema = cinema;
        this.seat = seat;
    }

    @Override
    public void run() {
        synchronized (cinema) {
            boolean flag = cinema.bookTicket(seat);
            if (flag) {
                System.out.println(Thread.currentThread().getName() + ",购票成功...." + seat);
            } else {
                System.out.println(Thread.currentThread().getName() + "购票失败....位置不够，购票数" + seat);
            }
        }

    }
}


/**
 * 影院
 */
class Cinema {
    private int available;
    private String name;

    public Cinema(int available, String name) {
        this.available = available;
        this.name = name;
    }

    public boolean bookTicket(int seat) {
        System.out.println("-------->可用位置" + available);
        if (seat > available) {
            return false;
        }
        available -= seat;
        return true;
    }
}
